/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.WebIDE.ejb.sessions;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.transaction.UserTransaction;
import org.WebIDE.ejb.entities.GroupsResources;
import org.WebIDE.ejb.entities.*;
import org.WebIDE.ejb.entities.Resources;
import org.WebIDE.ejb.sessions.exceptions.IllegalOrphanException;
import org.WebIDE.ejb.sessions.exceptions.NonexistentEntityException;
import org.WebIDE.ejb.sessions.exceptions.PreexistingEntityException;
import org.WebIDE.ejb.sessions.exceptions.RollbackFailureException;

/**
 *
 * @author huy
 */
@Stateless
public class ResourcesFacade implements ResourcesFacadeLocal, ResourcesFacadeRemote {
    @PersistenceContext
    private EntityManager _em;
    @Resource
    private UserTransaction utx = null;
    @PersistenceUnit(unitName = "WebIDE-ejbPU")
    private EntityManagerFactory emf = null;
/*
    public void create(Resources resources) {
        _em.persist(resources);
    }

    public void edit(Resources resources) {
        _em.merge(resources);
    }
*/
    public void remove(Resources resources) {
        _em.remove(_em.merge(resources));
    }

    public Resources find(Object id) {
        return _em.find(Resources.class, id);
    }

    public List<Resources> findAll() {
        return _em.createQuery("select object(o) from Resources as o").getResultList();
    }


    public EntityManager getEntityManager() {
        return _em;
    }

    public void create(Resources resources) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (resources.getGroupsResourcesCollection() == null) {
            resources.setGroupsResourcesCollection(new ArrayList<GroupsResources>());
        }
        EntityManager em = null;
        try {
            //utx.begin();
            em = getEntityManager();
            Collection<GroupsResources> attachedGroupsResourcesCollection = new ArrayList<GroupsResources>();
            for (GroupsResources groupsResourcesCollectionGroupsResourcesToAttach : resources.getGroupsResourcesCollection()) {
                groupsResourcesCollectionGroupsResourcesToAttach = em.getReference(groupsResourcesCollectionGroupsResourcesToAttach.getClass(), groupsResourcesCollectionGroupsResourcesToAttach.getGroupsResourcesPK());
                attachedGroupsResourcesCollection.add(groupsResourcesCollectionGroupsResourcesToAttach);
            }
            resources.setGroupsResourcesCollection(attachedGroupsResourcesCollection);
            em.persist(resources);
            for (GroupsResources groupsResourcesCollectionGroupsResources : resources.getGroupsResourcesCollection()) {
                Resources oldResourcesOfGroupsResourcesCollectionGroupsResources = groupsResourcesCollectionGroupsResources.getResources();
                groupsResourcesCollectionGroupsResources.setResources(resources);
                groupsResourcesCollectionGroupsResources = em.merge(groupsResourcesCollectionGroupsResources);
                if (oldResourcesOfGroupsResourcesCollectionGroupsResources != null) {
                    oldResourcesOfGroupsResourcesCollectionGroupsResources.getGroupsResourcesCollection().remove(groupsResourcesCollectionGroupsResources);
                    oldResourcesOfGroupsResourcesCollectionGroupsResources = em.merge(oldResourcesOfGroupsResourcesCollectionGroupsResources);
                }
            }
            //utx.commit();
        } catch (Exception ex) {
            try {
                //utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findResources(resources.getId()) != null) {
                throw new PreexistingEntityException("Resources " + resources + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                //em.close();
            }
        }
    }

    public void edit(Resources resources) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            //utx.begin();
            em = getEntityManager();
            Resources persistentResources = em.find(Resources.class, resources.getId());
            Collection<GroupsResources> groupsResourcesCollectionOld = persistentResources.getGroupsResourcesCollection();
            Collection<GroupsResources> groupsResourcesCollectionNew = resources.getGroupsResourcesCollection();
            List<String> illegalOrphanMessages = null;
            for (GroupsResources groupsResourcesCollectionOldGroupsResources : groupsResourcesCollectionOld) {
                if (!groupsResourcesCollectionNew.contains(groupsResourcesCollectionOldGroupsResources)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain GroupsResources " + groupsResourcesCollectionOldGroupsResources + " since its resources field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<GroupsResources> attachedGroupsResourcesCollectionNew = new ArrayList<GroupsResources>();
            for (GroupsResources groupsResourcesCollectionNewGroupsResourcesToAttach : groupsResourcesCollectionNew) {
                groupsResourcesCollectionNewGroupsResourcesToAttach = em.getReference(groupsResourcesCollectionNewGroupsResourcesToAttach.getClass(), groupsResourcesCollectionNewGroupsResourcesToAttach.getGroupsResourcesPK());
                attachedGroupsResourcesCollectionNew.add(groupsResourcesCollectionNewGroupsResourcesToAttach);
            }
            groupsResourcesCollectionNew = attachedGroupsResourcesCollectionNew;
            resources.setGroupsResourcesCollection(groupsResourcesCollectionNew);
            resources = em.merge(resources);
            for (GroupsResources groupsResourcesCollectionNewGroupsResources : groupsResourcesCollectionNew) {
                if (!groupsResourcesCollectionOld.contains(groupsResourcesCollectionNewGroupsResources)) {
                    Resources oldResourcesOfGroupsResourcesCollectionNewGroupsResources = groupsResourcesCollectionNewGroupsResources.getResources();
                    groupsResourcesCollectionNewGroupsResources.setResources(resources);
                    groupsResourcesCollectionNewGroupsResources = em.merge(groupsResourcesCollectionNewGroupsResources);
                    if (oldResourcesOfGroupsResourcesCollectionNewGroupsResources != null && !oldResourcesOfGroupsResourcesCollectionNewGroupsResources.equals(resources)) {
                        oldResourcesOfGroupsResourcesCollectionNewGroupsResources.getGroupsResourcesCollection().remove(groupsResourcesCollectionNewGroupsResources);
                        oldResourcesOfGroupsResourcesCollectionNewGroupsResources = em.merge(oldResourcesOfGroupsResourcesCollectionNewGroupsResources);
                    }
                }
            }
            //utx.commit();
        } catch (Exception ex) {
            try {
                //utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = resources.getId();
                if (findResources(id) == null) {
                    throw new NonexistentEntityException("The resources with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                //em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            //utx.begin();
            em = getEntityManager();
            Resources resources;
            try {
                resources = em.getReference(Resources.class, id);
                resources.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The resources with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<GroupsResources> groupsResourcesCollectionOrphanCheck = resources.getGroupsResourcesCollection();
            for (GroupsResources groupsResourcesCollectionOrphanCheckGroupsResources : groupsResourcesCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Resources (" + resources + ") cannot be destroyed since the GroupsResources " + groupsResourcesCollectionOrphanCheckGroupsResources + " in its groupsResourcesCollection field has a non-nullable resources field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(resources);
            //utx.commit();
        } catch (Exception ex) {
            try {
                //utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                //em.close();
            }
        }
    }

    public List<Resources> findResourcesEntities() {
        return findResourcesEntities(true, -1, -1);
    }

    public List<Resources> findResourcesEntities(int maxResults, int firstResult) {
        return findResourcesEntities(false, maxResults, firstResult);
    }

    private List<Resources> findResourcesEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Resources as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            //em.close();
        }
    }

    public Resources findResources(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Resources.class, id);
        } finally {
            //em.close();
        }
    }

    public int getResourcesCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Resources as o").getSingleResult()).intValue();
        } finally {
            //em.close();
        }
    }

}
